package cmd

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"kubehark/kubehark-framwork/pkg/Data/DataSourceCrd"
	"kubehark/kubehark-framwork/pkg/HarkConfig"
	"kubehark/kubehark-framwork/pkg/K8sProxy"
	"kubehark/kubehark-framwork/pkg/Middlewares/UsePlugins"
	"kubehark/kubehark-framwork/pkg/Plugin/PluginFactory"
	"net/http"
	"os"
)

var CmdFlag *CmdServer

type CmdServer struct {
	ConfigPath string
}

func (this *CmdServer) SetFlag(command *cobra.Command) {
	command.Flags().StringVar(&this.ConfigPath, "configpath", "", "configpath")
}

func NewCmdServer() *cobra.Command {
	str := CmdServer{}
	CmdFlag = &str
	var Cmd = &cobra.Command{
		Use:   "server",
		Short: "server",
		Long:  `kubehark server端`,
		Run: func(cmd *cobra.Command, args []string) {
			// 初始化配置文件
			config,err :=HarkConfig.NewConfigFromPath(CmdFlag.ConfigPath)
			if err!= nil{
				fmt.Println(err.Error())
				os.Exit(1)
			}
			// 初始化 k8sclient
			DataSourceCrd.Init(config.RunningConfig.K8sConfig)
			// 初始化插件相关
			PluginFactory.InitPluginFactory(config.PluginConfig.PluginsConfig)
			PluginFactory.SetBefoUsePlugin(config.PluginConfig.UseBefoPlugins)
			PluginFactory.SetAfterPlugin(config.PluginConfig.UseAfterPlugins)
			router := gin.Default()
			gin.ForceConsoleColor()
			router.Any(
				"cluster/:clusterID/*proxyPath",
				UsePlugins.UsePlugins(),
				clusterProxy,
			)
			router.GET("switch/:clusterID",loginCluster)
			router.Any("health", func(context *gin.Context) {
				context.JSON(200,"ok")
			})
			router.RunTLS(fmt.Sprintf(":%s", config.RunningConfig.Port), config.RunningConfig.SSLKSecret, config.RunningConfig.SSLkey)
		},
	}
	str.SetFlag(Cmd)
	return Cmd
}

func clusterProxy(c *gin.Context) {
	clusterID := c.Param("clusterID")
	proxy,err := K8sProxy.GetProxyInfo(clusterID)
	if err != nil {
		c.JSON(http.StatusUnauthorized, metav1.Status{
			Code:    http.StatusUnauthorized,
			Message: err.Error(),
		})
		return
	}
	proxyPath := c.Param("proxyPath")
	proxy.DoHttpProxy(c.Writer, c.Request, proxyPath)

}

func loginCluster(c *gin.Context)  {
	clusterID := c.Param("clusterID")
	_,err := K8sProxy.GetProxyInfo(clusterID)
	fmt.Println(clusterID)
	if err!= nil{
		c.JSON(http.StatusNotFound, metav1.Status{
			Code:    http.StatusNotFound,
			Message: err.Error(),
		})

	}else {
		c.JSON(http.StatusOK, metav1.Status{
			Code:    http.StatusOK,
			Message: "登录成功",
		})
	}
}